package com.raibaz.atm.businesslogic;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.InputTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;

import android.util.Log;

public class AtmFetcher {

	public static ArrayList<Instruction> fetchPath(String from, String to) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://www.atm-mi.it/it/Giromilano/Pagine/default.aspx");
        
        try {
        	URL url = new URL("http://www.atm-mi.it/it/Giromilano/Pagine/default.aspx");        	
        	
        	HttpResponse getres = httpclient.execute(new HttpGet("http://www.atm-mi.it/it/Giromilano/Pagine/default.aspx"));
        	GregorianCalendar cutStart = new GregorianCalendar();
        	String firstRes = EntityUtils.toString(getres.getEntity());
        	String firstPart = firstRes.substring(firstRes.indexOf("<form"));
        	firstPart = firstPart.substring(0, firstPart.indexOf("<script"));
        	String secondPart = firstRes.substring(firstRes.indexOf("<div id=\"atm-footer\">"), firstRes.indexOf("</form>"));
        	firstRes = firstPart + secondPart + "</form>";
        	Log.i("timing", "tagliaecuci delle stringhe terminato in " + (new GregorianCalendar().getTimeInMillis() - cutStart.getTimeInMillis()) + " ms.");
        	Parser p = new Parser();
        	p.setInputHTML(firstRes);
        	        	
        	NodeClassFilter ncf = new NodeClassFilter(InputTag.class);        	        	
        	CssSelectorNodeFilter css = new CssSelectorNodeFilter("#__VIEWSTATE");
        	AndFilter and = new AndFilter(css, ncf);
        	HasAttributeFilter ev = new HasAttributeFilter("name", "__EVENTVALIDATION");
        	OrFilter or = new OrFilter(and, ev);
        	        	
        	String viewState = "";
        	String eventValidation = "";
        	GregorianCalendar parseStart = new GregorianCalendar();
        	NodeList nl = p.parse(or);
        	SimpleNodeIterator itr = nl.elements();
        	while(itr.hasMoreNodes()) {
        		Tag t = (Tag)itr.nextNode();
        		if(t.getAttribute("name").equals("__VIEWSTATE")) {
        			viewState = t.getAttribute("value");
        		} else if(t.getAttribute("name").equals("__EVENTVALIDATION")) {
        			eventValidation = t.getAttribute("value");
        		}
        	}
        	
        	Log.i("timing", "Parse di htmlparser completato in " + (new GregorianCalendar().getTimeInMillis() - parseStart.getTimeInMillis()) + " ms.");
        	        	        
        	
        	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
			//Your DATA 
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$txt_address_s", from)); 
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$txt_address_e", to));
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$txt_town_s", "milano"));
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$txt_town_e", "milano"));
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$bwsbm", "Calcola"));
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$bw_tp_mean_rbl", "1"));
			nameValuePairs.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_72c6ed04_5126_46da_af73_113fbfcc56e0$bw_bwtype_rbl", "0"));
			nameValuePairs.add(new BasicNameValuePair("__EVENTVALIDATION", eventValidation));
			nameValuePairs.add(new BasicNameValuePair("__VIEWSTATE", viewState));


			
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
			
			HttpResponse response; 
			response=httpclient.execute(post);
			String res = EntityUtils.toString(response.getEntity());
			res = res.substring(res.indexOf("<table class=\"tblResults\">"));
			res = res.substring(0, res.indexOf("</table>"));
			res = res.replace("<tr><tbody>", "<tbody><tr>");
			
			Log.e("response", res);
			p.reset();
			p.setInputHTML(res);
			HasAttributeFilter classRes = new HasAttributeFilter("class", "tblResults");
			parseStart = new GregorianCalendar();
			nl = p.parse(classRes);
			Log.i("timing", "Parse di htmlparser completato in " + (new GregorianCalendar().getTimeInMillis() - parseStart.getTimeInMillis()) + " ms.");
			ArrayList<Instruction> ret = new ArrayList<Instruction>();
			TableTag table = (TableTag)nl.elementAt(0);
			for(TableRow tr : table.getRows()) {
				for(TableColumn td : tr.getColumns()) {		
					String text = StringEscapeUtils.unescapeHtml(td.getStringText().replace("&nbsp;", "")).replaceAll("\\<[^>]*>","").trim();
					if(StringUtils.isNotBlank(text)) {
						ret.add(new Instruction(text));
					}
				}
			}
			return ret;
        } catch (Exception e) {
        	e.printStackTrace();
        	return new ArrayList<Instruction>();
        }	
	}	
}
